<template>
  <div class="container">
    <van-nav-bar title="点检" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <div class="saveBtnDiv">
      <van-button class="saveBtns" type="primary" native-type="submit" @click="submitForm(2)">提交转维修</van-button>
      <van-button class="saveBtns" style="margin-right:5px ;" type="primary" native-type="submit" @click="submitForm(1)">提交</van-button>
    </div>
    <div class="publicBox">
      <div class="checkInputTop">
        <div class="checkInputTopCont">
          <ul>
            <li class="liBai">
              <div>
                <b>设备</b>
                <em>
                  <van-field :value="`${detailsObj.equipName}${detailsObj.equipCode !== '' ? '【' + detailsObj.equipCode + '】': ''}`" readonly size="mini" />
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>上次检结果</b>
                <em>
                  <span :class="detailsObj.result ? detailsObj.result === 1 ? 'green' : 'red' :''" class="resultStyle">{{detailsObj.result ? detailsObj.result === 1 ? '通过':'不通过' : ''}}</span>
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>点检结果</b>
                <em>
                  <van-radio-group v-model="ruleForm.result" :disabled="ruleForm.disabled" class="radioStyle" direction="horizontal" style="margin-top:15px ;">
                    <van-radio :name="1" shape="square">通过</van-radio>
                    <van-radio :name="0" shape="square">不通过</van-radio>
                  </van-radio-group>
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>点检人</b>
                <em>
                  <van-field v-model="ruleForm.checkUserName" size="mini" readonly @click="showUser = true" />
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>点检时间</b>
                <em>
                  <van-cell-group>
                    <van-field v-model="ruleForm.checkTime" size="mini" readonly @click="selectTime()" />
                  </van-cell-group>
                </em>
              </div>
            </li>
          </ul>
          <div class="textareaDiv">
            <b>点检说明</b>
            <em>
              <van-field v-model="ruleForm.checkInstructions" rows="3" size="mini" type="textarea" maxlength="200" show-word-limit />
            </em>
          </div>
        </div>
      </div>
      <div class="qualityContent">
        <h1>点检项</h1>
        <div class="contentItem">
          <!-- 点检项 -->
          <inspection-items ref="inspectionItems" @resultChange="resultChange" :item-list="ruleForm.itemList" />
        </div>
      </div>
    </div>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>
    <!-- 人员选择 -->
    <van-popup v-model="showUser" position="bottom">
      <van-picker title="人员选择" show-toolbar :columns="userList" @confirm="onConfirm" @cancel="showUser = false" />
    </van-popup>
  </div>
</template>
<script>
import { myFunction } from '../../../../utils/function'
import inspectionItems from '../../component/inspectionItems'
export default {
  name: 'EquipmentInspection',
  components: { inspectionItems },
  data() {
    return {
      currentDate: new Date(),
      userList: [],
      itemList: [],
      ruleForm: {
        checkInstructions: '',
        disabled: false,
        itemList: [],
        result: 1,
        checkUserName: JSON.parse(localStorage.getItem('padUserInfo')).data
          .userName, // 检验人
        checkTime: myFunction(new Date()), // 检验时间
        checkUserId: JSON.parse(localStorage.getItem('padUserInfo')).data.userId // 本次检验
      },
      show: false,
      code: localStorage.getItem('code'),
      search: {
        current: 1,
        size: 5
      },
      list: [],
      loading: false,
      isLoading: false,
      detailsObj: {},
      showTime: false,
      showUser: false
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler(row) {}
    }
  },
  created() {
    // this.search.proBatchNo = this.$route.query.code
  },
  mounted() {
    this.getData()
  },
  methods: {
    async getData(row) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '数据加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      this.detailsObj = this.$store.state.data
      await this.getDetail()
      /* 获取人员 */
      await this.getUser()
      await this.getItemList(toast)
    },
    async getDetail() {
      const res = await this.$axios.get(
        `/dobo-equip/point/check/getCheck/${this.detailsObj.id}`
      )
      if (res?.data.code === 200) {
        this.detailsObj.result = res.data.data.result
      }
    },
    /* 获取所有人员 */
    async getUser() {
      const res = await this.$axios.get('/dobo-user/user/getAllUser')
      if (res.data.code === 200) {
        this.userLists = res.data.data
        res.data.data.forEach((item) => {
          this.userList.push(item.name)
        })
      }
    },
    resultChange(flag) {
      this.ruleForm.result = flag === true ? 1 : 0
      this.ruleForm.disabled = flag
    },
    /* 获取点检项 */
    async getItemList(toast) {
      console.log(this.detailsObj)
      const res = await this.$axios.get(
        `/dobo-equip/point/check/getCheckItem/${this.detailsObj.id}`
      )
      if (res.data.code === 200) {
        if (res.data.data.length < 1) {
          setTimeout(() => {
            toast.clear()
          }, 100)
          this.$dialog
            .alert({
              title: '提示',
              message: '当前数据没有点检项请维护点检项！'
            })
            .then(() => {
              this.$router.go(-1)
            })
          return
        } else {
          setTimeout(() => {
            toast.clear()
            res.data.data.forEach((item) => {
              item.itemResult = 1
            })
            this.ruleForm.itemList = res.data.data
          }, 10)
        }
      }
    },
    /* 选择时间 */
    selectTime() {
      this.showTime = true
    },
    /* 时间选择赋值 */
    onTimeChange(value) {
      this.ruleForm.checkTime = myFunction(value)
      this.showTime = false
    },
    /* 人员选择 */
    onConfirm(e) {
      let id = ''
      this.userLists.forEach((item) => {
        if (item.name === e) id = item.id
      })
      this.ruleForm.checkUserId = id
      this.ruleForm.checkUserName = e
      this.showUser = false
    },
    sum(arr) {
      return arr.reduce(function (prev, curr, idx, arr) {
        return prev + curr
      })
    },
    submitForms() {
      this.$router.push('/repairRequest')
      this.$store.commit('getDate', this.detailsObj)
    },
    submitForm(num) {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否确认提交？'
        })
        .then(() => {
          this.ruleForm.itemList.forEach((item) => {
            if (item.fileList) {
              item.fileIds = []
              item.fileList.forEach((itx) => {
                item.fileIds.push(itx.fileId)
              })
            }
          })
          this.submitApi(num)
        })
        .catch(() => {
          return false
        })
    },
    submitApi(num) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '提交中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      this.ruleForm.equipName = this.detailsObj.equipName
      this.ruleForm.equipCode = this.detailsObj.equipCode
      this.ruleForm.id = this.detailsObj.id
      console.log(this.ruleForm)
      this.$axios
        .post('/dobo-equip/point/check/point/check', this.ruleForm)
        .then((res) => {
          if (res.data.code === 200) {
            toast.clear()
            this.$dialog
              .alert({
                title: '提示',
                message: '提交成功!'
              })
              .then(() => {
                if (num === 1) {
                  this.$router.push('/equipmentInspection')
                } else {
                  this.detailsObj.nums = 1
                  this.$router.push('/repairRequest')
                  this.$store.commit('getDate', this.detailsObj)
                }
              })
              .catch(() => {})
          } else {
            this.$toast.fail(res.data.msg)
            setTimeout(() => {
              toast.clear()
              this.$router.push('/equipmentInspection')
            }, 1000)
          }
        })
        .catch(() => {})
    },
    // 返回
    onClickLeft() {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/equipmentInspection')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .checkInputTopCont {
    ul {
      .liBai {
        width: 100% !important;
        .van-cell {
          width: 98% !important;
        }
      }
    }
  }
  .qualityContent {
    height: calc(100% - 290px);
    overflow: hidden;
    h1 {
      height: 40px;
      line-height: 40px;
      font-weight: normal;
      text-align: center;
      background: #eeee;
      color: #022566;
    }
    .contentItem {
      height: calc(100% - 40px);
      overflow-y: auto;
    }
  }
  /* 上次点检结果样式 */
  .resultStyle {
    width: calc(100% - 11px);
    height: 29px;
    line-height: 29px;
    font-size: 20px;
    padding-left: 10px;
    display: block;
    margin: 6px 8px 6px 0;
    color: #fff;
    border-radius: 10px;
  }
  /* 点检说明样式 */
  .textareaDiv {
    margin-top: 5px;
    b {
      width: 120px;
      display: block;
      font-weight: normal;
      float: left;
      height: 45px;
      line-height: 45px;
      text-align: center;
      font-size: 22px;
    }
    em {
      font-style: normal;
      display: block;
      width: calc(100% - 120px);
      float: left;
      height: 100%;
      .van-cell {
        // margin-top: 5px;
        border: 1px solid rgb(228, 228, 228) !important;
        border-radius: 10px;
        padding: 7px 10px;
        width: 98%;
        font-size: 22px;
      }
    }
  }
  .saveBtnDiv {
    position: absolute;
    right: 10px;
    top: 10px;
    width: 200px;
    height: 40px;
    text-align: right;
  }
}
</style>
<style lang='scss'>
// 提交按钮样式
.saveBtnDiv {
  .saveBtns {
    float: right;
    font-size: 16px;
    z-index: 102;
    height: 40px;
    line-height: 40px;
    background: linear-gradient(to top right, #1cacff, #022566);
    border: 1px solid #022566;
    padding: 0 12px;
    .van-button__content {
      display: block;

      .van-button__text {
        text-align: center;
        width: 100%;
        font-size: 20px;
      }
    }
  }
}
</style>
